package inventory;

import impsoft.scripting.ibot.builtin.itemrec.InventorySlotSelector2;
import impsoft.scripting.ibot.enums.InventorySlot;
import impsoft.scripting.ibot.itemrec.ItemCondition;
import impsoft.scripting.ibot.itemrec.ItemContainsAny;
import impsoft.scripting.ibot.itemrec.ItemContainsIgnore;
import impsoft.utils.general.Timer;

import java.util.EnumSet;

import base.DreamScript;
import base.DreamUtility;
import conditions.ItemEqualsAny;

public class InventoryUtils extends DreamUtility {

	public static final ItemCondition BONES = new ItemContainsIgnore("bones", new String[] { "bones to peaches",
			"Bones to peaches", "Bones to Peaches", "Bones To Peaches", "Peach" });
	public static final ItemCondition ASHES = new ItemContainsAny(new String[] { "Impious ashes", "Accursed ashes",
			"Infernal ashes" });

	public InventoryUtils(DreamScript cs) {
		super(cs);
	}

	public void doActionOnAll(ItemCondition condition, String action) throws InterruptedException {
		InventorySlot slot = null;
		InventorySlotSelector2 selector = InventorySlotSelector2.DEFAULT;
		Timer actionTimer = new Timer(60000);

		if (cs.random(1, 3) == 2) {
			selector = InventorySlotSelector2.SORT_BY_DOWNARD_SLOT_ORDER;
		} else {
			selector = InventorySlotSelector2.SORT_BY_UPWARD_SLOT_ORDER;
		}

		int total = 0;
		while (actionTimer.isNotUp() && (slot = selector.select(getSlots(condition), cs)) != null && total != 28) {
			cs.theTabs.Inventory2.doAction(slot, action, false);
			if (cs.random(0, 21) > 1) {
				cs.sleep(900, 1200);
			} else {
				cs.sleep(3000, 4000);
			}

			total++;
		}
	}

	private EnumSet<InventorySlot> getSlots(ItemCondition condition) throws InterruptedException {
		EnumSet<InventorySlot> slots = EnumSet.noneOf(InventorySlot.class);

		for (InventorySlot slot : getSlots()) {
			String itemName = cs.theTabs.Inventory2.getName(slot);

			if (itemName != null && condition.validItem(itemName)) {
				slots.add(slot);
			}
		}

		return slots;
	}

	private EnumSet<InventorySlot> getSlots() {
		return EnumSet.allOf(InventorySlot.class);
	}

	public InventoryResult doInventory(String item, String action, boolean waitForChange) throws InterruptedException {
		return doInventory(new ItemEqualsAny(item), action, waitForChange);
	}

	public InventoryResult doInventory(ItemCondition ic, String action, boolean waitForChange)
			throws InterruptedException {
		return new InventoryResult(cs.theTabs.Inventory2.doAction(ic, action, 1, waitForChange) == 1, null);
	}
}
